﻿using Microsoft.AspNetCore.Mvc.Filters;
using RuoVea.ExDto;
using RuoVea.ExFilter.Config;
using RuoVea.ExUtil;
using RuoVea.ExUtil.Exceptions;
using RuoVea.ExUtil.Time;

namespace RuoVea.ExFilter;

/// <summary>
/// 接口安全校验
/// </summary>
public class SafeFilter : IAsyncActionFilter, IOrderedFilter
{
    /// <summary>
    /// 排序
    /// </summary>
    public int Order => 6;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // 执行 Action 并获取结果
        var actionContext = await next();
        RestfulResult restfulResult = new RestfulResult();

        var request = context.HttpContext.Request;
        var appKey = ""; //客户端应用唯一标识
        long timeStamp; //时间戳， 校验5分钟内有效

        "接口安全校验 - 检查 appKey timeStamp".WriteInfoLine();

        string[] appKeys = ExFilterConfigs.FilterOptions?.AppKeys;
        if (appKeys == null)
            throw new ParamiterException("AppKeys IS NULL,请设置");

        appKey = request.Headers[ExFilterConfigs.FilterOptions.AppKeyName].SingleOrDefault();

        if (appKey == null)
        {
            "非法请求-k".WriteInfoLine();
            throw new ParamiterException("非法请求-k");
        }
        if (!appKeys.Contains(appKey)) throw new ParamiterException("非法请求");

        string timeStampsStr = request.Headers[ExFilterConfigs.FilterOptions.TimeStampName].SingleOrDefault();
        if (timeStampsStr == null) throw new ParamiterException("非法请求");

        timeStamp = Convert.ToInt64(timeStampsStr);

        //判断timespan是否有效，请求是否超时
        DateTime tonow = UnixTime.ToDateTime(timeStamp);
        var expires_minute = tonow.Minute - DateTime.Now.Minute;
        if (expires_minute > ExFilterConfigs.FilterOptions.ExpiresMinute || expires_minute < -ExFilterConfigs.FilterOptions.ExpiresMinute)
        {
            throw new ParamiterException("接口请求超时");
        }
    }
}
